package com.qst.controller;

import com.qst.*;
import com.qst.action.question.QuestionHelper;
import com.qst.action.question.QuestionQueryParam;
import com.qst.entity.*;
import com.qst.service.AssessmentService;
import com.qst.service.DimensionService;
import com.qst.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/question")
public class QuestionController extends BaseServlet {

    private final QuestionService questionService;
    private final AssessmentService assessmentService;
    private final DimensionService dimensionService;

    //使用构造函数注入bean
    @Autowired
    public QuestionController(@Qualifier("questionServiceSsmImpl") QuestionService questionService,
                              @Qualifier("assessmentServiceSsmImpl") AssessmentService assessmentService,
                              @Qualifier("dimensionServiceSsmImpl") DimensionService dimensionService) {
        this.questionService = questionService;
        this.assessmentService = assessmentService;
        this.dimensionService = dimensionService;
    }

    //题目列表
    @RequestMapping("/list.action")
    public String list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数用于判断做添加操作还是查询列表操作
        String submitButton = RequestUtil.getString(req, "create");
        if (!submitButton.isEmpty())
        {
            return doCreate(req, resp);
        } else {
            return doList(req, resp);
        }
    }

    //题目详情
    @RequestMapping("/view.action")
    public String view(HttpServletRequest req) throws ServletException, IOException {
        //根据题目id获取对应题目信息
        Question question = questionService.findById(RequestUtil.getInt(req, "id"));
        //根据题目id获取该题目选项信息
        List<Choice> choices = questionService.findChoices(question.getId());
        //根据题目中的AssessmentId获取该题目对应的考核类型
        AssessmentType assessment = assessmentService.findAssessmentById(question.getAssessmentId());
        //根据题目id获取该题目关联的性格维度信息
        List<PersonalityDimension> dimension = questionService.findDimensionByQuestion(question.getId());

        req.setAttribute("assessment", assessment);
        req.setAttribute("question", question);
        req.setAttribute("choices", choices);
        req.setAttribute("dimension", dimension);
        return "/question/view";
    }

    //保存新增题目信息
    @RequestMapping("/save.action")
    public String save(HttpServletRequest req) throws ServletException, IOException {
        Question question = QuestionHelper.createQuestion(req);
        List<Choice> choices = QuestionHelper.createChoice(req);
        try {
            User currentUser = (User) req.getSession().getAttribute(Constant.CURRENT_USER);
            question.setUserId(currentUser.getId());
            questionService.save(question, choices);
            addMessage(req, "试题保存到数据库中");
            //WebUtil.redirect(req, resp, "/question/dimension.action?id=" + question.getId());
            return "forward:/question/dimension.action?id=" + question.getId();
        } catch (ExamException ex) {
            System.out.println(ex);
            addError(req, ex.getMessage());
            req.setAttribute("question", question);
            req.setAttribute("choices", choices);
            req.setAttribute("assessment", assessmentService.findAssessmentById(question.getAssessmentId()));
            //WebUtil.forward(req, resp, "/question/create.jsp");
            return "/question/create";
        }
    }

    //关联性格维度
    @RequestMapping("/dimension.action")
    public String dimension(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = RequestUtil.getString(req, "method");

        if ("save".equals(method)) {
            return saveQuestion(req, resp);
        } else {
            return editQuestion(req, resp);
        }
    }

    //跳转修改题目界面
    @RequestMapping("/edit.action")
    public String edit(HttpServletRequest req) throws ServletException, IOException {
        Question question = questionService.findById(RequestUtil.getInt(req, "id"));
        List<Choice> choices = questionService.findChoices(question.getId());
        AssessmentType assessment = assessmentService.findAssessmentById(question.getAssessmentId());
        req.setAttribute("assessment", assessment);
        req.setAttribute("question", question);
        req.setAttribute("choices", choices);
        //WebUtil.forward(req, resp, "/question/edit.jsp");
        return "/question/edit";
    }

    //修改题目详情
    @RequestMapping("/update.action")
    public String update(HttpServletRequest req) throws ServletException, IOException {
        Question question = QuestionHelper.createQuestion(req);
        List<Choice> choices = QuestionHelper.createChoice(req);
        try {
            User currentUser = (User) req.getSession().getAttribute(Constant.CURRENT_USER);
            question.setUserId(currentUser.getId());
            questionService.update(question, choices);
            addMessage(req, "题目已经保存到数据库中,请关联性格维度");
            //WebUtil.redirect(req, resp, "/question/dimension.action?method=show&id=" + question.getId());
            return "forward:/question/dimension.action?method=show&id=" + question.getId();
        } catch (ExamException ex) {
            addError(req, ex.getMessage());
            req.setAttribute("question", question);
            req.setAttribute("choices", choices);
            req.setAttribute("assessment", assessmentService.findAssessmentById(question.getAssessmentId()));
            //WebUtil.forward(req, resp, "/question/edit.jsp");
            return "/question/edit";
        }
    }

    //删除题目
    @RequestMapping("/delete.action")
    public String delete(HttpServletRequest req) throws ServletException, IOException {
        int id = RequestUtil.getInt(req, "id");
        Question q = questionService.findById(id);
        try {
            questionService.delete(id);
            addMessage(req, "题目已删除");
        } catch (ExamException ex) {
            addError(req, ex.getMessage());
        }
        return "forward:/question/list.action?assessmentId=" + q.getAssessmentId() + "&status="
                + q.getStatus() + "&type=" + q.getType();
    }


    private String doList(HttpServletRequest req, HttpServletResponse resp) {
        //查询所有考核类型
        List<AssessmentType> assessmentList = assessmentService.findAllAssessment();
        req.setAttribute("assessmentList", assessmentList);

        QuestionQueryParam param = QuestionQueryParam.create(req);
        req.setAttribute("query", param);

        List<Question> questionList = questionService.find(param);
        req.setAttribute("questionList", questionList);
        return "question/list";
    }
    private String doCreate(HttpServletRequest req, HttpServletResponse resp) {
        QuestionQueryParam param = QuestionQueryParam.create(req);
        req.setAttribute("assessment",
                assessmentService.findAssessmentById(param.getAssessmentId()));
        Question question = new Question();
        question.setType(param.getType());
        question.setDifficulty(4);
        req.setAttribute("question", question);
        return "question/create";
    }
    protected String saveQuestion(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        int qid = RequestUtil.getInt(req, "id");
        if(qid==0){
            qid=RequestUtil.getInt(req, "qid");
        }
        int[] pids = RequestUtil.getIntArray(req, "pid");
        if(pids==null){
            Question question = questionService.findById(qid);
            List<PersonalityDimension> dimensionList = dimensionService.findDimensionByAssessment(question.getAssessmentId());
            req.setAttribute("dimensionList", dimensionList);
            List<Integer> attachedDimension = questionService.findDimensionIdByQuestion(qid);
            for (PersonalityDimension p : dimensionList) {
                p.getExtras().put("checked", attachedDimension.contains(p.getId()) ? "checked" : "");
            }
            req.setAttribute("error", "你还未关联任何维度！");
            req.setAttribute("qid", qid);
            //WebUtil.forward(req, resp, "/question/dimension.jsp");
            return "/question/dimension";
        }
        questionService.attachDimension(qid, pids);
        //WebUtil.redirect(req, resp, "/question/view.action?id=" + qid);
        return "redirect:/question/view.action?id=" + qid;
    }
    protected String editQuestion(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        int id = RequestUtil.getInt(req, "id");
        Question question = questionService.findById(id);
        req.setAttribute("question", question);
        List<PersonalityDimension> dimensionList = dimensionService.findDimensionByAssessment(question.getAssessmentId());
        req.setAttribute("dimensionList", dimensionList);
        List<Integer> attachedDimension = questionService.findDimensionIdByQuestion(id);
        for (PersonalityDimension p : dimensionList) {
            p.getExtras().put("checked", attachedDimension.contains(p.getId()) ? "checked" : "");
        }
        //WebUtil.forward(req, resp, "/question/dimension.jsp");
        return "/question/dimension";
    }

}
